<?php

use console\db\Migration;
use yii\helpers\Json;
use console\models\BaseDist;
use yii\helpers\Console;

/**
 * 创建应用基础相关信息数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200104_091354_d_base_dist extends Migration {

    const BASE_CODE = '100000';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $tablename = BaseDist::tableName();
        if ($this->isExistsTable($tablename)) {
            $this->truncateTable($tablename);
        }
        $data = $this->getData('dist.json');

        $province = $data[self::BASE_CODE];
        $rows = [];
        $parent_id = 0;
        $level = 1;

        $count = count($data) + 1;
        Console::startProgress($i = 0, $count);
        foreach ($province as $code => $name) {
            $rows[] = compact('parent_id', 'level', 'code', 'name');
            Console::startProgress($i = 0, count($province));
        }
        $this->saveDist($rows);
        Console::updateProgress( ++$i, $count);
        unset($data[self::BASE_CODE]);

        foreach ($data as $key => $item) {
            $parent = BaseDist::find()->where(['code' => $key])->one();
            $rows = [];
            $parent_id = $parent->id;
            $level = $parent->level + 1;
            foreach ($item as $code => $name) {
                $rows[] = compact('parent_id', 'level', 'code', 'name');
            }
            $this->saveDist($rows);
            Console::updateProgress( ++$i, $count);
        }
        Console::endProgress("update done." . PHP_EOL);
    }

    /**
     * @inheritdoc
     */
    protected function saveDist($rows) {
        $this->batchInsert(BaseDist::tableName(), [
            'parent_id',
            'level',
            'code',
            'name',
        ], $rows);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $tablename = BaseDist::tableName();
        if ($this->isExistsTable($tablename)) {
            $this->truncateTable($tablename);
        }
    }

}
